package com.ge.down;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @BelongsProject: SpringMVC
 * @BelongsPackage: com.ge.down
 * @Author: gejingyu
 * @Date: 2024/1/16
 * @Description: 文件下载
 */

@Controller
@RequestMapping("/down")
public class DownController {

    @RequestMapping("/test")
    public ResponseEntity<byte[]> testDown(HttpSession session) throws IOException {

        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取文件在服务器中的真实路径
        String realPath = servletContext.getRealPath("/文件路径");
        //创建输入流
        FileInputStream inputStream = new FileInputStream(realPath);
        //创建字节数组
        byte[] bytes = new byte[inputStream.available()];
        //将流读入到数组中
        inputStream.read(bytes);
        //创建HttpHeaders对象设置响应头
        MultiValueMap<String, String> headers = new HttpHeaders();
        //设置下载方式及下载文件的名字
        headers.add("Content-Disposition", "attachment:filename=文件名");
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        //创建响应报文对象
        ResponseEntity<byte[]> response = new ResponseEntity<>(bytes, headers, statusCode);
        //关闭输入流
        inputStream.close();
        return response;
    }
}
